<template>
  <div ref="dom"></div>
</template>

<script>
import echarts from "echarts";
import { on, off } from "@/libs/tools";
import { getHomeOrderStatistic } from "@/api/form";

export default {
  data() {
    return {
      dom: null
    };
  },
  props: {
    dataRange: Object
  },
  methods: {
    resize() {
      this.dom.resize();
    },
    setOption(callback, data = {}) {
      const option = {
        title: {
          text: "月订单量走势"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: []
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "秒杀订单",
            type: "line",
            stack: "总量",
            data: []
          },
          {
            name: "团购订单",
            type: "line",
            stack: "总量",
            data: []
          }
        ]
      };

      0 && getHomeOrderStatistic(data).then(res => {
        const data = res.data.data;
        option.legend.data = Array.from(new Set(data.map(c => c.name)));
        option.xAxis.data = Array.from(new Set(data.map(c => c.x)));
        option.series = option.legend.data.map(leg => {
          return {
            name: leg,
            type: "line",
            stack: "总量",
            data: data.filter(d => d.name === leg).map(c => c.y)
          };
        });
        callback && callback(option);
      });
    }
  },
  mounted() {
    this.setOption(option => {
      this.$nextTick(() => {
        this.dom = echarts.init(this.$refs.dom);
        this.dom.setOption(option);
        on(window, "resize", this.resize);
      });
    });
  },
  beforeDestroy() {
    off(window, "resize", this.resize);
  },
  watch: {
    dataRange(newDataRange) {
      this.setOption(option => {
        this.dom.setOption(option);
      },newDataRange);
    }
  }
};
</script>
